//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "ATTraining\fn_createTarget.sqf"
#include <core_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private ["_type","_direction","_distance","_lane","_lane_name","_array","_marker","_current","_vehicle","_marker_dest","_vehicle_array","_crew","_group","_wp"];
DEFAULT_PARAM(_type,0,"");
DEFAULT_PARAM(_direction,1,0);
DEFAULT_PARAM(_distance,2,0);
DEFAULT_PARAM(_lane,3,0);

_lane_name = "MOVING";
_array = GVAR(TRAINING_TARGETS_MOVING);
switch (_lane) do {
	case 1: {_lane_name = "LEFT";_array = GVAR(TRAINING_TARGETS_LEFT);};
	case 3: {_lane_name = "RIGHT";_array = GVAR(TRAINING_TARGETS_RIGHT);};
};

if (isServer) then {
	_current = _array select (_distance - 1);
	if (count _current > 0) then {
		{
			_x removeAllEventHandlers "HandleDamage";
			deleteVehicle _x;
		} foreach _current;
	};
	_marker_name = FORMAT["AT_%1_%2",_lane_name,_distance];
	TRACE_1("Creation",ARR_3(_marker_name,_type,_direction));
	_current = [];
	if (_lane != 2) then {
		_vehicle = ["",_type,[0,0,1000]] call TMF_fnc_createVehicle;
		_vehicle addEventHandler ["HandleDamage",FUNC(ehHandleDamage)];
		_vehicle enableSimulation false;
		_vehicle setVelocity [0,0,0];
		_vehicle setPos (markerpos _marker_name);
		_vehicle setDir _direction;
		_current = [_vehicle];
	} else {
		_marker_name = FORMAT["AT_LEFT_%1",_distance];
		_marker_dest = FORMAT["AT_RIGHT_%1",_distance];
		_vehicle_array = ["",_type,"EAST",(markerpos _marker_name)] call TMF_fnc_spawnVehicle;
		TRACE_1("Spawned",_vehicle_array);
		//[_veh, _crew, _grp]
		if (count _vehicle_array > 0) then {
			_vehicle = GETVAL(_vehicle_array,0,objNull);
			_crew = GETVAL(_vehicle_array,1,[]);
			_group = GETVAL(_vehicle_array,2,grpNull);
			{
				_x addEventHandler ["HandleDamage",{0}];
				_x disableAI "AUTOTARGET";
				_current set [count _current, _x];
			} foreach _crew;
			// Some cleanup...
			{
				if (_x isKindOf "Man" && vehicle _x == _x) then {
					deleteVehicle _x;
				};
			} foreach (units _group);
			
			_vehicle addEventHandler ["HandleDamage",FUNC(ehHandleDamage)];
			_current set [count _current, _vehicle];
			
			_group setBehaviour "CARELESS";
			_group setSpeedMode "NORMAL";
			_group setCombatMode "WHITE";
			_current set [count _current, _group];
			
			[_group] call TMF_fnc_deleteWaypoints;
			_wp = _group addWayPoint [(markerPos _marker_name),20];
			_wp setWaypointType "MOVE";
			_wp = _group addWayPoint [(markerPos _marker_dest),20];
			_wp setWaypointType "MOVE";
			_wp = _group addWayPoint [(markerPos _marker_name),20];
			_wp setWaypointType "CYCLE";
			_wp setWaypointSpeed "NORMAL";
		};
	};
	TRACE_1("Created Target",_current);
	_array set [(_distance - 1),_current];
} else {
	_array set [(_distance - 1),[true]];
};

TRACE("End");
TMFPROFILERSTOP;
